/**
 * Created by Aimee on 14-11-10.
 */
define(['jquery', 'jquerymobile', 'net', 'dialogs', 'activity_verify'], function($, m, net, dia, activityVerify) {
    var m_activity = null;

    //保存需要确认的报名信息
    var m_activity_needStr = null;

    var p_pageFrom = null;

    var p_backFrom = null;

    // 补充0
    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    function getMonthString(month) {
        month = month + 1;
        if (month == 1)
            return 'Jan';
        else if (month == 2)
            return 'Feb';
        else if (month == 3)
            return 'Mar';
        else if (month == 4)
            return 'Apr';
        else if (month == 5)
            return 'May';
        else if (month == 6)
            return 'June';
        else if (month == 7)
            return 'July';
        else if (month == 8)
            return 'Aug';
        else if (month == 9)
            return 'Sept';
        else if (month == 10)
            return 'Oct';
        else if (month == 11)
            return 'Nov';
        else if (month == 12)
            return 'Dec';
        else {
            console.assert(false, '月份 %o 不存在 ', month );
        }
    }

    //获取注册活动 基本信息
    function getAcvtivities(activity) {
        var value = activity;

        //解析报名信息
        var need_info = null;
        need_info = value.enroll_need;
        console.assert(need_info != null, '必须有报名文本框显示 %o', need_info);
        var needArr = need_info.split('==');

        console.log('各文本框的属性：%o', needArr);

        if ($('#activityRegister_list li').length != 1) {
            $('#activityRegister_list li:first').remove();
        }
        //获取活动
        var startDate = new Date(value.startTime * 1000);
        var endDate = new Date(value.endTime * 1000);
        var startTime = 'Start: ' + pad(startDate.getHours(), 2) + ':' + pad(startDate.getMinutes(),2) + ', ' + startDate.getDate() + " " + getMonthString(startDate.getMonth()) + " " + startDate.getFullYear();
        var endTime = 'End: ' + pad(endDate.getHours(),2) + ':' + pad(endDate.getMinutes(),2) + ', ' + endDate.getDate() + " " + getMonthString(endDate.getMonth()) + " " + endDate.getFullYear();
        var venue = 'Venue: ' + value.venue;
        var li = creatActivity(value.subject, startTime, endTime, venue, needArr);
        $(li).insertBefore($('#activityRegister_list li:first'));
    }

    function valueForIndex(index) {
        var cuser = null;
        if (localStorage.getItem('login_user')!=null) {
            cuser = JSON.parse(localStorage.getItem('login_user'));
        } else {
            console.assert(false, '还没登录，没有用户信息可填写');
        }

        if (index == 0) {
            return cuser.staffId;
        } else if (index == 1) {
            return cuser.english_name;
        } else if (index == 2) {
            return cuser.chinese_name;
        }else if (index == 3) {
            return cuser.email;
        }

        return null;
    }

    //创建活动
    function creatActivity(subject, startTime, endTime, venue, needArr) {
        var html_text = '';
        if(needArr != null){
            var i = 0;
            $.each(needArr, function(index, val) {
                var nameArr = val.split(":");
                console.log('nameAttr: %o', nameArr);
                if(nameArr[1] == 'yes') {
                    var fValue = valueForIndex(index) != null ? valueForIndex(index) : "";
                    if (index < 4) {
                        html_text += html_text = '<!--'+ nameArr[0] +'\-->\
                                    <div style="border: none;padding: 10px;">\
                                        <div style="font-family: Arial;font-size: 14px;font-weight: normal;color: #404040;margin-bottom: 10px">'+ nameArr[0] +'\ <span style="color:red;">*</span></div>\
                                        <input data-role="none" id="activityRegister_txt_id_'+ i +'\_" type="text" style="width: 100%;height: 44px;font-family: Arial;font-size: 12px;font-weight: bold;color: #404040;padding: 14px;border: solid 1px #D2D2D2;border-radius: 0px" readonly="readonly" value="'+fValue+'"/>\
                                    </div>';
                    } else {
                        html_text += html_text = '<!--'+ nameArr[0] +'\-->\
                                    <div style="border: none;padding: 10px;">\
                                        <div style="font-family: Arial;font-size: 14px;font-weight: normal;color: #404040;margin-bottom: 10px">'+ nameArr[0] +'\ <span style="color:red;">*</span></div>\
                                        <input data-role="none" id="activityRegister_txt_id_'+ i +'\_" type="text" style="width: 100%;height: 44px;font-family: Arial;font-size: 12px;font-weight: bold;color: #404040;padding: 14px;border: solid 1px #D2D2D2;border-radius: 0px" value="'+fValue+'"/>\
                                    </div>';
                    }

                    i++;
                } else if(nameArr[1] == 'no'){
                    html_text += html_text = '<!--'+ index +'\-->\
                                    <div style="border: none;padding: 10px;">\
                                        <div style="font-family: Arial;font-size: 14px;font-weight: normal;color: #404040;margin-bottom: 10px">'+ nameArr[0] +'\</div>\
                                        <input data-role="none" id="activityRegister_txt_id_'+ i +'\_" type="text" style="width: 100%;height: 44px;font-family: Arial;font-size: 12px;font-weight: bold;color: #404040;padding: 14px;border: solid 1px #D2D2D2;border-radius: 0px"/>\
                                    </div>';
                    i++;
                } else {
                    console.log(false, '文本框只有必填和非必填两种可能');
                }
            });
        } else {
            console.assert(needArr != null, '文本框为空 %o', needArr);
        }

        var html = '\<li style="padding: 0px;">\
            <!--标题图-->\
            <div style="width:100%;  padding: 0; border: none;background-color: rgb(101,153,193);">\
                <div style="width:100%;padding: 20px 10px 10px 10px">\
                    <div style="white-space:normal;font-weight: normal;font-size: 18px;color: #ffffff;margin-bottom: 8px">'+ subject +'\</div>\
                    <div style="font-size: 11px;color: #ffffff;line-height: 18px;font-weight: normal">\
                        <span style="display: block;white-space:normal;">'+ startTime +'\</span>\
                        <span style="display: block;white-space:normal;">'+ endTime +'\</span>\
                        <span style="display: block;white-space:normal;">'+ venue +'\</span>\
                    </div>\
                </div>\
            </div>\
             '+ html_text +'\
            \</li>';
        return html;
    }

    //返回 显示所有活动的页面
    $('#activityRegister_btn_back').off('click')
        .on('click',function() {
            p_backFrom == null;
            $.mobile.newChangePage(p_pageFrom, { transition: "slide", reverse: true, changeHash:false});
        });

    //进入注册确认页面
    $('#btn_activityRegister').off('click')
        .on('click', function() {
            p_backFrom = null;
            activityVerify.edit(function(type){
                if (type == 'edit') {
                    p_backFrom = type;
                } else if (type == 'cancel') {
                    p_backFrom = type;
                } else {
                    console.assert(false, '从报名确认页面返回回来的方式不可能是%s', type);
                }
                console.log(type);
            });
            activityVerify.showActivity(m_activity);
            //禁用按钮
//            $('#btn_activityRegister').attr("disabled","disabled");
            var messages="";
            var needStr="";
            var needArrayText = '';
            var needNameStr="";
            var activity_enroll_need = m_activity.enroll_need;
            var needInfo = activity_enroll_need.split('==');
            var i = 0;
            $.each(needInfo, function(index, val) {
               var needAttr = val.split(':');
               var text_val=$('#activityRegister_txt_id_'+ i +'_').val();
               if(text_val==null || text_val=="" || text_val==undefined){
                   text_val="";
               }

                //判断text_val不能包含＝  ， ： ［   ］

                //判断必填项
               var name_isNotNulls  =  needInfo[index].split(":");
               if(name_isNotNulls!=null && name_isNotNulls!="" && name_isNotNulls!=undefined){
                   if(name_isNotNulls.length==2) {
                       if (name_isNotNulls[1] == "yes") {
                           if (text_val == "") {
                               messages="Please fill up all the mandatory fields.";
                               return false;
                           }
                       }
                   } else
                   {
                       messages="Server error, please try again.";
                       return false;
                   }
                   needStr+=needInfo[index]+":"+text_val+"==";
               }

                console.log('文本框内容 %o', $('#activityRegister_txt_id_'+ i +'_').val());
                i++;
            });
            if(messages!=""){
                dia.alert("Oops!",messages, ['OK'], function () {
                                   return false;

                });
            }else{
                needStr=needStr.substring(0,needStr.length-2);
//                window.q['verify_needStr'] = needStr;
                m_activity_needStr = needStr;
                activityVerify.showNeedStr(needStr);
                console.log("最终数据 ％o"+needStr);
                $.mobile.newChangePage("#activityVerify",{ transition: "slide",reverse: false,changeHash: false});
            }
        });

    function edit_registerInfo() {
        var value = m_activity;
        //解析报名信息
        var need_info = m_activity_needStr;
        console.assert(need_info != null, '必须有报名文本框显示 %o', need_info);
        var needArr = need_info.split('==');

        console.log('各文本框的属性：%o', needArr);
        //获取活动
        var startDate = new Date(value.startTime * 1000);
        var endDate = new Date(value.endTime * 1000);
        var startTime = 'Start:' + pad(startDate.getHours(), 2) + ':' + pad(startDate.getMinutes(),2) + ',' + startDate.toLocaleDateString();
        var endTime = 'End:' + pad(endDate.getHours(),2) + ':' + pad(endDate.getMinutes(),2) + ',' + endDate.toLocaleDateString();
        var venue = 'Venue:' + value.venue;
        var li = creat_editActivity(value.subject, startTime, endTime, venue, needArr);
        $(li).insertBefore($('#activityRegister_list li:first'));

    }

    //创建活动
    function creat_editActivity(subject, startTime, endTime, venue, needArr) {
        var html_text = '';
        if(needArr != null){
            var i = 0;
            $.each(needArr, function(index, val) {
                var nameArr = val.split(":");
                console.log('nameAttr: %o', nameArr);
                if(nameArr[1] == 'yes') {
                    html_text += html_text = '<!--'+ nameArr[0] +'\-->\
                                    <div style="border: none;padding: 10px;">\
                                        <div style="font-family: Arial;font-size: 14px;font-weight: normal;color: #404040;margin-bottom: 10px">'+ nameArr[0] +'\ <span style="color:red;">*</span></div>\
                                        <input data-role="none" id="activityRegister_txt_id_'+ i +'\_" type="text" style="width: 100%;height: 44px;font-family: Arial;font-size: 12px;font-weight: bold;color: #404040;padding: 14px;border: solid 1px #D2D2D2;border-radius: 0px" value='+ nameArr[2] +'\;/>\
                                    </div>';
                    i++;
                } else if(nameArr[1] == 'no'){
                    html_text += html_text = '<!--'+ index +'\-->\
                                    <div style="border: none;padding: 10px;">\
                                        <div style="font-family: Arial;font-size: 14px;font-weight: normal;color: #404040;margin-bottom: 10px">'+ nameArr[0] +'\ <span style="color:black;">*</span></div>\
                                        <input data-role="none" id="activityRegister_txt_id_'+ i +'\_" type="text" style="width: 100%;height: 44px;font-family: Arial;font-size: 12px;font-weight: bold;color: #404040;padding: 14px;border: solid 1px #D2D2D2;border-radius: 0px" value='+ nameArr[2] +'\;/>\
                                    </div>';
                    i++;
                } else {
                    console.log(false, '文本框只有必填和非必填两种可能');
                }
            });
        } else {
            console.assert(needArr != null, '文本框为空 %o', needArr);
        }

        var html = '\<li style="padding: 0px;">\
            <!--标题图-->\
            <div style="width:100%;  padding: 0; border: none;background-color: rgb(101,153,193);">\
                <div style="width:100%;padding: 20px 10px 10px 10px">\
                    <div style="white-space:normal;font-weight: normal;font-size: 18px;color: #ffffff;margin-bottom: 8px">'+ subject +'\</div>\
                    <div style="font-size: 11px;color: #ffffff;line-height: 18px;font-weight: normal">\
                        <span style="display: block">'+ startTime +'\</span>\
                        <span style="display: block">'+ endTime +'\</span>\
                        <span style="display: block">'+ venue +'\</span>\
                    </div>\
                </div>\
            </div>\
             '+ html_text +'\
            \</li>';
        return html;
    }

    $('#activityRegister').on('pageshow', function(event) {
        window.setBodyOverflow($(document.body));
        $('#activityRegister_content').css('height',($(window).height()-40));

        if (p_pageFrom == '#newsroom' ||
            p_pageFrom == '#activities' ||
            p_pageFrom == '#activity_detail') {
                if (p_backFrom == null){
                    getAcvtivities(m_activity);
                }
        }

    });

    $("#activityRegister").on( "pagehide", function( event ) {
        p_backFrom = null;
    });

    return {
        setAcvtivities: function (acvtivitie) {
            m_activity = acvtivitie;
        },
        from: function(pageFrom) {
            p_pageFrom = pageFrom;
			window.pageFrom = pageFrom;//add for register activity confirm page ok button back action
        }
    }
});